﻿//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//using System.Text.RegularExpressions;
//using System.Json;
//using PQ.Model;

//namespace WebQQ2.DLL
//{
//    /// <summary>
//    /// 2011-1-5
//    /// by hackren
//    /// Email:hackren@vip.qq.com
//    /// </summary>
//    [Serializable]
//    public class WebQQCommon
//    {
//        public delegate void FriendMessageHandler(string fuin, string message);
//        public event FriendMessageHandler OnFriendMessageEvent;

//        public delegate void QunMessageHandler(string groupCode, string sendTempUin, string message, string fontStyle);
//        public event QunMessageHandler OnQunMessageEvent;

//        public delegate void AddFriendHandler(string fuin, string message);
//        public event AddFriendHandler OnAddFriendEvent;

//        private static readonly string[] AVATAR_SERVER_DOMAINS = new[] { "http://face1.qun.qq.com/", "http://face2.qun.qq.com/", "http://face3.qun.qq.com/", "http://face4.qun.qq.com/", "http://face5.qun.qq.com/", "http://face6.qun.qq.com/", "http://face7.qun.qq.com/", "http://face8.qun.qq.com/", "http://face9.qun.qq.com/", "http://face10.qun.qq.com/" };
//        private static readonly string RefUrl = "http://s.web2.qq.com/proxy.html?v=20101025002";
//        public UserEntity user;
//       // HttpHelper httpHelper = new HttpHelper();
//        /// <summary>
//        /// 构造
//        /// </summary>
//        /// <param name="user"></param>
//        public WebQQCommon(userEntity user)
//        {
//            user.Cookie = new System.Net.CookieContainer();
//            this.user = user;
//        }

//        /// <summary>
//        /// 构造
//        /// </summary>
//        /// <param name="user"></param>
//        public WebQQCommon(userEntity user, System.Net.IWebProxy proxy)
//        {
//            user.Cookie = new System.Net.CookieContainer();
//            if (proxy != null)
//                httpHelper.Proxy = proxy;
//            this.user = user;
//        }

         


//        /// <summary>
//        /// 判断是否需要验证码
//        /// http://ptlogin2.qq.com/check?uin=415516174&appid=15000101&r=0.8178552857537984
//        /// uin为QQ号码
//        /// appid没弄清干什么的，在我这里不会改变
//        /// r为16位随机小数
//        ///返回格式 ptui_checkVC('0','!XGB');  ptui_checkVC('1','d3831928a037b4fb5a5336936989e6a607a4edb0ed6da139');
//        ///0代表不需要输入验证码，验证码为！XGB
//        ///1代表需要验证码，后边会跟48位的密文，应该是个算子，在获取验证码的时候要用到
//        /// </summary>
//        /// <returns>返回为需要验证码吗，当返回true时需要结合user.VerifyCode32是否为空去最后判断是否需要</returns>
//        public bool IsNeedVerifyCode()
//        {
//            string url = String.Format("http://ptlogin2.qq.com/check?uin={0}&appid={1}&r={2}", user.Username, user.appid, Utils.getRadomNum().ToString());
//            string result = httpHelper.GetHtml(url, user.Cookie);
//            if (result.Contains("\'0\'"))
//            {
//                string vc = "";
//                try
//                {
//                    vc = result.Substring(result.LastIndexOf("\'") - 4, 4);
//                }
//                catch (Exception)
//                {
//                }
//                user.VerifyCode = vc;
//                return false;
//            }
//            else if (result.Contains("\'1\'"))
//            {
//                string vc = "";
//                try
//                {
//                    vc = result.Substring(result.LastIndexOf("\'") - 48, 48);
//                }
//                catch (Exception)
//                {

//                }
//                user.VerifyCode32 = vc;
//                return true;
//            }
//            else
//            {
//                return true;
//            }
//        }

//        /// <summary>
//        /// 返回验证码的图片流
//        /// 验证码的获取地址的构成需要48位的算子，需要在判断是否需要验证码时获取
//        /// </summary>
//        /// <returns></returns>
//        public System.IO.Stream getVerifyCodePicStream()
//        {
//            System.IO.Stream result = null;
//            try
//            {
//                string url = String.Format("http://captcha.qq.com/getimage?aid={0}&r={1}&uin={2}&vc_type={3}", user.appid, Utils.getRadomNum().ToString(), user.Username, user.VerifyCode32);
//                result = httpHelper.GetStream(url, user.Cookie);
//            }
//            catch (Exception)
//            {

//            }
//            return result;
//        }


//        /// <summary>
//        /// 获取即时消息
//        /// </summary>
//        public void GetMessage()
//        {
//            string url = string.Format("http://d.web2.qq.com/channel/poll2?clientid={0}&psessionid={1}&t={2}", user.ClientId, user.Psessionid, WebQQUtil.GetTime(DateTime.Now).ToString());
//            string result = httpHelper.GetHtml(url, user.Cookie);

//            try
//            {
//                JsonObject message = (JsonObject)JsonValue.Parse(result);
//                if (message["retcode"].ToString() == "0")
//                {
//                    foreach (JsonObject item in message["result"])
//                    {
//                        string type = item["poll_type"].ToString().Replace("\"", "");

//                        switch (type)
//                        {
//                            case "message":
//                                InitFriendMessageEvent(item);
//                                break;
//                            case "system_message":
//                                InitAddFriendEvent(item);
//                                break;
//                            case "group_message":
//                                InitGroupMessageEvent(item);
//                                break;
//                            default:
//                                break;
//                        }
//                    }
//                }
//            }
//            catch (Exception)
//            {

//            }
//        }

//        /// <summary>
//        /// 获取好友及好友分组
//        /// </summary>
//        /// <returns></returns>
//        public bool GetUserFriends()
//        {
//            user.Groups = new Dictionary<int, string>();
//            user.Friends = new Dictionary<string, Friend>();
//            string url = "http://web2-b.qq.com/api/get_user_friends";
//            string data = string.Format("r=%7B%22vfwebqq%22%3A%22{0}%22%7D", user.Key);
//            string result = httpHelper.GetHtml(url, data, true, user.Cookie, url);

//            Regex group = new Regex("({\"index\":)(?<index>[0-9]{1,2}?)(,\"name\":\")(?<name>.+?)(\"})");
//            foreach (Match item in group.Matches(result))
//            {
//                user.Groups.Add(Convert.ToInt32(item.Groups["index"].Value), Utils.ConvertUnicodeStringToChinese(item.Groups["name"].Value));
//            }

//            Regex friend = new Regex("({\"uin\":)(?<uin>[0-9]{5,11}?)(,\"categories\":)(?<id>[0-9]{1,2}?)(})");
//            foreach (Match item in friend.Matches(result))
//            {
//                Friend f = new Friend();
//                f.Uin = item.Groups["uin"].Value;
//                f.GroupId = Convert.ToInt32(item.Groups["id"].Value);
//                user.Friends.Add(f.Uin, f);
//            }

//            Regex info = new Regex("({\"uin\":)(?<uin>[0-9]{5,11}?)(,\"nick\":\")(?<nick>.+?)(\",\"face\":)(?<face>.+?)(,\"flag\":)(?<flag>.+?)(})");
//            foreach (Match item in info.Matches(result))
//            {
//                if (user.Friends.Keys.Contains(item.Groups["uin"].Value))
//                {
//                    user.Friends[item.Groups["uin"].Value].Nick = Utils.ConvertUnicodeStringToChinese(item.Groups["nick"].Value);
//                    user.Friends[item.Groups["uin"].Value].FaceImg = item.Groups["face"].Value;

//                }


//            }
//            return false;
//        }

//        /// <summary>
//        /// 给好友发送消息
//        /// </summary>
//        /// <param name="friendUin"></param>
//        /// <param name="message"></param>
//        /// <returns></returns>
//        public bool sendFriendMessage(string friendUin, string message)
//        {
//            string url = "http://web2-b.qq.com/channel/send_msg";
//            string postData = string.Format("r=%7B%22to%22%3A{0}%2C%22face%22%3A528%2C%22content%22%3A%22%5B%5C%22{1}%5C%22%2C%5B%5C%22font%5C%22%2C%7B%5C%22name%5C%22%3A%5C%22%E5%AE%8B%E4%BD%93%5C%22%2C%5C%22size%5C%22%3A%5C%2210%5C%22%2C%5C%22style%5C%22%3A%5B0%2C0%2C0%5D%2C%5C%22color%5C%22%3A%5C%22000000%5C%22%7D%5D%5D%22%2C%22msg_id%22%3A42530002%2C%22clientid%22%3A%22{2}%22%2C%22psessionid%22%3A%22{3}%22%7D"
//                , friendUin, Utils.StrConvUrlEncoding(message, "utf-8"), user.ClientId, user.Psessionid);

//            string result = httpHelper.GetHtml(url, postData, true, user.Cookie, " http://web2-b.qq.com/proxy.html?v=20101025002");
//            if (result.Contains("retcode\":0"))
//                return true;
//            else
//                return false;
//        }

//        /// <summary>
//        /// 给所有好友发送消息，间隔10秒
//        /// </summary>
//        /// <param name="message"></param>
//        public void SendMessageForAllFriend(string message)
//        {
//            if (user.Friends.Count <= 0)
//                GetUserFriends();
//            foreach (string uin in user.Friends.Keys)
//            {
//                sendFriendMessage(uin, message);
//                System.Threading.Thread.Sleep(10000);
//            }
//        }

//        /// <summary>
//        /// 修改个性签名
//        /// </summary>
//        /// <param name="message"></param>
//        /// <returns></returns>
//        public bool SetLongNick(string message)
//        {
//            string url = "http://web2-b.qq.com/api/set_long_nick";
//            string postDate = string.Format("r=%7B%22nlk%22%3A%22{0}%22%2C%22vfwebqq%22%3A%22{1}%22%7D", Utils.StrConvUrlEncoding(message, "utf-8"), user.Key);

//            string result = httpHelper.GetHtml(url, postDate, true, user.Cookie, url);
//            if (result.Contains("retcode\":0"))
//                return true;
//            else
//                return false;
//        }

//        /// <summary>
//        /// 修改资料（昵称，网址，个性说明）
//        /// </summary>
//        /// <param name="nickName"></param>
//        /// <param name="homeUrl"></param>
//        /// <param name="shuoming"></param>
//        /// <returns></returns>
//        public bool ModifyMyInfo(string nickName, string homeUrl, string shuoming)
//        {
//            string url = "http://web2-b.qq.com/api/modify_my_details";
//            string postDate = string.Format("r=%7B%22nick%22%3A%22{0}%22%2C%22gender%22%3A%22female"
//                + "%22%2C%22shengxiao%22%3A%221%22%2C%22constel%22%3A%221%22%2C%22blood%22%3A%221%22%2C%22"
//                + "birthyear%22%3A%221989%22%2C%22birthmonth%22%3A%2211%22%2C%22birthday%22%3A%221%22%2C%22"
//                + "phone%22%3A%2201022222222%22%2C%22mobile%22%3A%2213111111122%22%2C%22email%22%3A%22abcde%40qq.com%22%2C%22"
//                + "occupation%22%3A%22hack%22%2C%22college%22%3A%22beida%22%2C%22homepage%22%3A%22{1}%22%2C%22personal%22%3A%22"
//                + "{2}%22%2C%22vfwebqq%22%3A%22{3}%22%7D", Utils.StrConvUrlEncoding(nickName, "utf-8"), Utils.StrConvUrlEncoding(homeUrl, "utf-8"), Utils.StrConvUrlEncoding(shuoming, "utf-8"), user.Key);

//            string result = httpHelper.GetHtml(url, postDate, true, user.Cookie, url);
//            if (result.Contains("retcode\":0"))
//                return true;
//            else
//                return false;
//        }

//        /// <summary>
//        /// 退出
//        /// </summary>
//        public void LogOut()
//        {
//            string url = "http://web2-b.qq.com/channel/login";
//            string postData = string.Format("r=%7B%22status%22%3A%22%22%2C%22ptwebqq%22%3A%22{0}%22%2C%22passwd_sig%22%3A%22%22%2C%22clientid%22%3A%22{1}%22%7D"
//                                            , user.ptwebqq, user.ClientId);

//            string result = httpHelper.GetHtml(url, postData, true, user.Cookie, url);
//        }

//        /// <summary>
//        /// 隐身
//        /// </summary>
//        public void ChangeStatus(OnlineStatusEnum status)
//        {
//            string state = "online";
//            switch (status)
//            {
//                case OnlineStatusEnum.Online:
//                    state = "online";
//                    break;
//                case OnlineStatusEnum.Away:
//                    state = "away";
//                    break;
//                case OnlineStatusEnum.Hidden:
//                    state = "hidden";
//                    break;
//                case OnlineStatusEnum.Offline:
//                    state = "offine";
//                    break;
//                default:
//                    state = "online";
//                    break;
//            }
//            string url = string.Format("http://web2-b.qq.com/channel/change_status?newstatus={0}&clientid={1}&psessionid={2}&t={3}", state, user.ClientId, user.Psessionid, WebQQUtil.GetTime(DateTime.Now));
//            string result = httpHelper.GetHtml(url, user.Cookie);
//        }


//        /// <summary>
//        /// 获取头像服务器
//        /// </summary>
//        /// <param name="qq"></param>
//        /// <returns></returns>
//        public string GetFaceServer(int qq)
//        {
//            return AVATAR_SERVER_DOMAINS[qq % 10];
//        }
//        /// <summary>
//        /// 获取用户头像
//        /// </summary>
//        /// <param name="qq"></param>
//        /// <returns></returns>
//        public System.IO.Stream GetUserAvatar(string qq)
//        {
//            return httpHelper.GetStream(GetFaceServer(Convert.ToInt32(qq)) + "cgi/svr/face/getface?cache=0&type=1&fid=0&uin=" + qq, user.Cookie);
//        }


//        /// <summary>
//        /// 获取用户的详细信息
//        /// </summary>
//        /// <param name="buddy"></param>
//        /// <returns></returns>
//        public userEntity GetSingleInfo(string uin)
//        {
//            userEntity buddy = new userEntity();
//            string url = string.Format("http://web2-b.qq.com/api/get_single_info?tuin={0}&t={1}", uin,
//                                       WebQQUtil.GetTime(DateTime.Now));

//            string html = httpHelper.GetHtml(url, user.Cookie);
//            // _logger.Debug("---------\r\nget请求url:{0} html:{1}", url, html);

//            var json = (JsonObject)JsonValue.Parse(html);
//            int retcode = json["retcode"];
//            if (retcode == 0)
//            {
//                var item = (JsonObject)json["result"];
//                //buddy.Status = QQHelper.ParseOnlineStatus(item["stat"]);
//                buddy.NickName = item["nick"];
//                //buddy.Country = item["country"];
//                // buddy.PersonalElucidation = item["province"];
//                //buddy.City = item["city"];
//                //buddy.Sex = item["gender"];
//                //buddy.Face = item["face"];
//                //var birthday = (JsonObject)item["birthday"];
//                //int year = birthday["year"];
//                //int month = birthday["month"];
//                //int day = birthday["day"];
//                //buddy.Birthday = new DateTime(year, month, day);
//                //buddy.Allow = item["allow"];
//                //buddy.Blood = item["blood"];
//                //buddy.ShengXiao = item["shengxiao"];
//                //buddy.Constel = item["constel"];
//                buddy.TelePhone = item["phone"];
//                buddy.MPhone = item["mobile"];
//                buddy.Email = item["email"];
//                //buddy.Occupation = item["occupation"];
//                //buddy.College = item["college"];
//                buddy.HomeUrl = item["homepage"];
//                buddy.PersonalElucidation = item["personal"];

//            }
//            return buddy;
//        }


//        /// <summary>
//        /// 触发加好友事件
//        /// </summary>
//        /// <param name="jsObject"></param>
//        private void InitAddFriendEvent(JsonValue jsObject)
//        {
//            if (jsObject != null)
//            {
//                JsonValue item = jsObject["value"];
//                if (OnAddFriendEvent != null)
//                    OnAddFriendEvent(item["from_uin"].ToString(), item.ContainsKey("msg") == false ? "" : item["msg"].ToString());

//                Console.WriteLine(item["from_uin"].ToString() + "------------------" + item["msg"].ToString());
//            }
//        }

//        /// <summary>
//        /// 触发收到好友消息事件
//        /// </summary>
//        /// <param name="jsObject"></param>
//        private void InitFriendMessageEvent(JsonValue jsObject)
//        {
//            if (jsObject != null)
//            {
//                JsonValue item = jsObject["value"];
//                if (OnFriendMessageEvent != null)
//                    OnFriendMessageEvent(item["from_uin"].ToString(), item["content"].ToString());
//                Console.WriteLine(item["from_uin"].ToString() + "----------" + item["content"].ToString());
//            }
//        }

//        /// <summary>
//        /// 触发收到群消息事件
//        /// </summary>
//        /// <param name="jsObject"></param>
//        private void InitGroupMessageEvent(JsonValue jsObject)
//        {
//            if (jsObject != null)
//            {
//                JsonValue item = jsObject["value"];

//                string groupCode = item["group_code"].ToString();
//                string sendUin = item["send_uin"].ToString();
//                string fontStyle = item["content"][0].ToString();
//                string message = item["content"].ToString().Replace(fontStyle, "");
//                if (message.Substring(0, 4) == "[,[\"")
//                {
//                    message = "s" + message;
//                    message = message.Insert(3, "\",");
//                }

//                if (message.Substring(message.Length - 2) == "]]")
//                {
//                    message = message.Substring(0, message.Length - 1) + ",\". s";
//                }
//                message = message.Substring(3, message.Length - 5).Replace("\\", "\\\\").Replace("\"", "\\\"");

//                if (message.Contains("\\\"cface\\\""))
//                    message = "机器人暂不能转发图片！";

//                if (OnQunMessageEvent != null)
//                    OnQunMessageEvent(groupCode, sendUin, message, fontStyle);
//            }
//        }

//        /// <summary>
//        /// 添加好友
//        /// </summary>
//        /// <param name="fuin">好友号码</param>
//        /// <returns></returns>
//        public bool AddFriend(string fuin)
//        {
//            string url = "http://web2-b.qq.com/api/allow_and_add";
//            string postData = string.Format("r=%7B%22tuin%22%3A{0}%2C%22gid%22%3A0%2C%22mname%22%3A%22%22%2C%22vfwebqq%22%3A%22{1}%22%7D", fuin, user.Key);

//            string result = httpHelper.GetHtml(url, postData, true, user.Cookie, RefUrl);

//            if (result.Contains("retcode\":0"))
//                return true;
//            else
//                return false;
//        }

//        /// <summary>
//        /// 获取群成员信息
//        /// </summary>
//        /// <param name="groupCode"></param>
//        /// <returns></returns>
//        public Dictionary<string, Friend> GetGroupminfos(string groupCode)
//        {
//            string url = string.Format("http://s.web2.qq.com/api/get_group_info_ext2?gcode={0}&vfwebqq={1}&t={2}", groupCode, user.Key, WebQQUtil.GetTime(DateTime.Now));

//            string result = httpHelper.GetHtml(url, user.Cookie);

//            Dictionary<string, Friend> friends = new Dictionary<string, Friend>();

//            try
//            {
//                JsonObject message = (JsonObject)JsonValue.Parse(result);
//                if (message["retcode"].ToString() == "0")
//                {
//                    JsonObject minfos = (JsonObject)JsonValue.Parse(message["result"].ToString());
//                    string ss = minfos.ToString();
//                    foreach (JsonObject item in minfos["minfo"])
//                    {
//                        try
//                        {
//                            Friend friend = new Friend();
//                            friend.TempUin = item["uin"].ToString();

//                            friend.Nick = item["nick"].ToString().TrimStart('"').TrimEnd('"'); ;

//                            friends.Add(friend.TempUin, friend);
//                        }
//                        catch (Exception)
//                        {
//                            continue;
//                        }
//                    }
//                    foreach (JsonObject item in minfos["cards"])
//                    {
//                        try
//                        {
//                            Friend friend = friends[item["muin"].ToString()];
//                            if (friend != null)
//                            {
//                                friend.CardName = item["card"].ToString().TrimStart('"').TrimEnd('"');
//                            }
//                        }
//                        catch (Exception)
//                        {
//                            continue;
//                        }
//                    }
//                }
//            }
//            catch (Exception)
//            {

//            }

//            return friends;
//        }

//        /// <summary>
//        /// 获取群列表及信息
//        /// </summary>
//        public void InitQunList()
//        {
//            string url = "http://s.web2.qq.com/api/get_group_name_list_mask2";
//            string postdata = string.Format("r=%7B%22vfwebqq%22%3A%22{0}%22%7D", user.Key);

//            string result = httpHelper.GetHtml(url, postdata, true, user.Cookie, RefUrl);
//            user.Quns = new Dictionary<string, QunEntity>();
//            try
//            {
//                JsonObject message = (JsonObject)JsonValue.Parse(result);
//                if (message["retcode"].ToString() == "0")
//                {
//                    JsonObject minfos = (JsonObject)JsonValue.Parse(message["result"].ToString());
//                    foreach (JsonObject item in minfos["gnamelist"])
//                    {
//                        try
//                        {
//                            QunEntity qun = new QunEntity();
//                            qun.GroupId = item["gid"].ToString();
//                            qun.GroupCode = item["code"].ToString();
//                            qun.GroupName = item["name"].ToString().Replace("\"", "");
//                            qun.QunMemberInfo = GetGroupminfos(qun.GroupCode);
//                            user.Quns.Add(qun.GroupCode, qun);

//                        }
//                        catch (Exception)
//                        {
//                            continue;
//                        }
//                    }
//                }
//            }
//            catch (Exception)
//            {

//            }
//        }

//        public bool SendGroupMessage(string qunCode, string message, string fontStyle)
//        {
//            string url = "http://d.web2.qq.com/channel/send_group_msg2";
//            string postData = string.Format("r=%7B%22group_uin%22%3A{0}%2C%22content%22%3A%22%5B%5C%22{1}%5C%22%2C%5B%5C%22font%5C%22%2C%7B%5C%22name%5C%22%3A%5C%22%E5%AE%8B%E4%BD%93%5C%22%2C%5C%22size%5C%22%3A%5C%2210%5C%22%2C%5C%22style%5C%22%3A%5B0%2C0%2C0%5D%2C%5C%22color%5C%22%3A%5C%22000000%5C%22%7D%5D%5D%22%2C%22msg_id%22%3A28380002%2C%22clientid%22%3A%22{2}%22%2C%22psessionid%22%3A%22{3}%22%7D"
//                , qunCode, Utils.StrConvUrlEncoding(message, "utf-8"), user.ClientId, user.Psessionid);
//            if (fontStyle != null)
//            {
//                postData = string.Format("r=%7B%22group_uin%22%3A{0}%2C%22content%22%3A%22%5B%5C%22{1}%5C%22%2C{2}%5D%22%2C%22msg_id%22%3A28380002%2C%22clientid%22%3A%22{3}%22%2C%22psessionid%22%3A%22{4}%22%7D"
//                , qunCode, Utils.StrConvUrlEncoding(message, "utf-8"), Utils.StrConvUrlEncoding(fontStyle.Replace("\"", "\\\""), "utf-8"), user.ClientId, user.Psessionid);
//            }

//            string result = httpHelper.GetHtml(url, postData, true, user.Cookie, RefUrl);
//            if (result.Contains("retcode\":0"))
//                return true;
//            else
//                return false;
//        }


//    }
//}
